package com.atm.bulksms;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.atm.bulksms.data.ContactItem;
import com.atm.bulksms.data.BulkSMSData.GroupData;
import com.atm.bulksms.data.BulkSMSData.InboxData;
import com.atm.bulksms.data.BulkSMSData.SMSData;
import com.atm.bulksms.util.Constants;
import com.atm.bulksms.util.Utils;

public class BulkSMSActivity extends Activity implements OnClickListener{
	EditText messageEditText;
	public static final byte STATUS_SENDING = 0;
	public static final byte STATUS_SENT = 1;
	public static final byte STATUS_RECEIVED = 2;
	int totalRecepient;
	RecipientListView groupLayout ;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        messageEditText = (EditText) findViewById(R.id.enter_msg);
        groupLayout = new RecipientListView(this, R.id.selected_recipients_list);
        
        Button send = (Button) findViewById(R.id.send_message);
        send.setOnClickListener(this);
        //Utils.setSelectedContacts(null);
        Utils.removeAllContacts();
        
        Button status = (Button) findViewById(R.id.status);
        status.setOnClickListener(this);
        
        Button groupBtn = (Button) findViewById(R.id.group_btn);
        groupBtn.setOnClickListener(this);
        
        Button scheduleBtn = (Button) findViewById(R.id.schedule_btn);
        scheduleBtn.setOnClickListener(this);
    }
    
    @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
    	//load recipients List
    	groupLayout.loadSelectedContacts();
		register();
    }
    
    @Override
    protected void onPause() {
    	// TODO Auto-generated method stub
    	super.onPause();
    	unregisterReceiver(receiver_sent);
    	unregisterReceiver(receiver_receive);
    }

	protected void sendSMS() {
		//Hashtable<Integer, ContactItem> selectedIndividuals = Utils.getSelectedContacts();
		//Hashtable<String, Vector<ContactItem>> selectedGroups = Utils.getSelectedGroups();
		totalRecepient = Utils.getSelectedRecipientCount();
               
                String message = messageEditText.getText().toString();
                if (TextUtils.isEmpty(message)) {
                	
                    Toast.makeText(this, "Enter a message to send.",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (totalRecepient == 0) {
                	Bundle bundle = new Bundle();
    				bundle.putString(Constants.TITLE, "Info");
    				bundle.putString(Constants.MESSAGE, "No recipients added.");
    				showDialog(Constants.DIALOG_MESSAGE, bundle);
                    Toast.makeText(this, "No recepient added.",
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                
                messageEditText.setEnabled(false);
              
                showDialog(Constants.DIALOG_PROGRESSBAR);
                
               
                
                long startTime = System.currentTimeMillis();
        		int currentCount = 0;
        		
        		Enumeration<ContactItem> items = (Enumeration<ContactItem>)Utils.getSelectedContacts().elements();
        		while (items.hasMoreElements()) {
        			sendSMS(items.nextElement(), ++currentCount, message, startTime);
        		}
        		
        		Enumeration<Vector<ContactItem>> groupItems = (Enumeration<Vector<ContactItem>>)Utils.getSelectedGroups().elements();
        		while (groupItems.hasMoreElements()) {
        			Vector<ContactItem> contactItems = groupItems.nextElement();
        			for (ContactItem contactItem : contactItems) {
        				sendSMS(contactItem, ++currentCount, message, startTime);
        			}
        		}
        		
        		/*if(names.length() > 1){
        			names.deleteCharAt(names.length() - 1);
        		}*/
        		ContentValues headerValues = new ContentValues();
        		headerValues.put(InboxData.NAME,"Name");
        		headerValues.put(InboxData.DESCRIPTION, message);
        		headerValues.put(InboxData.START_TIME, startTime);
        		getContentResolver().insert(InboxData.CONTENT_URI, headerValues);
	}
	
	
	//---when the SMS has been sent---
	BroadcastReceiver receiver_sent = new BroadcastReceiver(){
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			switch (getResultCode())
			{
			case Activity.RESULT_OK:
				Bundle extra = arg1.getExtras();
				if(extra != null){
					String phone = extra.getString(Constants.RECEIVER);
					int currentCount = extra.getInt(Constants.COUNT);
					long time = extra.getLong(Constants.SENDING_TIME);
					if(phone != null){
						System.out.println("phone  "+phone);
					}
					System.out.println("receiver sent :: currentCount "+currentCount+" totalRecepient "+totalRecepient);
					updateHandler.obtainMessage(MESSAGE_UPDATE_PREOGRESS_BAR_TEXT, "Message sent to :"+phone+" ("+currentCount+"/"+totalRecepient+")").sendToTarget();
					if(currentCount == totalRecepient){
						updateHandler.sendEmptyMessage(MESSAGE_PREOGRESS_DISMIS);
						messageEditText.setEnabled(true);
//	              			  Utils.setSelectedContacts(null);
						if(totalRecepient > 1){
							showDialog(Constants.DIALOG_STORE_GROUP);
						}
					}
					// Toast.makeText(getBaseContext(), "SMS sent ", 
					//		  Toast.LENGTH_SHORT).show();
					ContentValues values = new ContentValues();
					values.put(SMSData.STATUS, STATUS_SENT);
					getContentResolver().update(SMSData.CONTENT_URI, values, SMSData.SENT_TIME+"="+time+" AND "+SMSData.RECEPIENT+"="+phone, null);
					
				}
				break;
			case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
				Toast.makeText(getBaseContext(), "Generic failure", 
						Toast.LENGTH_SHORT).show();
				break;
			case SmsManager.RESULT_ERROR_NO_SERVICE:
				Toast.makeText(getBaseContext(), "No service", 
						Toast.LENGTH_SHORT).show();
				break;
			case SmsManager.RESULT_ERROR_NULL_PDU:
				Toast.makeText(getBaseContext(), "Null PDU", 
						Toast.LENGTH_SHORT).show();
				break;
			case SmsManager.RESULT_ERROR_RADIO_OFF:
				Toast.makeText(getBaseContext(), "Radio off", 
						Toast.LENGTH_SHORT).show();
				break;
			}
			// unregisterReceiver(this);
		}
	};
	//---when the SMS has been delivered---
	BroadcastReceiver receiver_receive = new BroadcastReceiver(){
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			switch (getResultCode())
			{
			case Activity.RESULT_OK:
				Toast.makeText(getBaseContext(), "SMS delivered ", 
						Toast.LENGTH_SHORT).show();
				Bundle extra = arg1.getExtras();
				if(extra != null){
					String phone = extra.getString(Constants.RECEIVER);
					long time = extra.getLong(Constants.SENDING_TIME);
					if(phone != null){
						System.out.println("phone  "+phone);
					}
					ContentValues values = new ContentValues();
					values.put(SMSData.STATUS, STATUS_RECEIVED);
					getContentResolver().update(SMSData.CONTENT_URI, values, SMSData.SENT_TIME+"="+time+" AND "+SMSData.RECEPIENT+"="+phone, null);
				}
				break;
			case Activity.RESULT_CANCELED:
				Toast.makeText(getBaseContext(), "SMS not delivered", 
						Toast.LENGTH_SHORT).show();
				break;                        
			}
			// unregisterReceiver(this);
		}
	};
	
  private void register() {
		  registerReceiver(receiver_sent, new IntentFilter(SENT));
		  registerReceiver(receiver_receive,new IntentFilter(DELIVERED));  
	}

  String SENT = "SMS_SENT";
  String DELIVERED = "SMS_DELIVERED";
  //SmsManager sms ;
	//---sends an SMS message to another device---
	
    
    private void sendSMS(ContactItem type, int currentCount, String message, long startTime) {

//		ContactItem type = (ContactItem) items.nextElement();
		System.out.println(" AddressItem : "+type);
		String name = type.getName();
		Vector<String> nos = type.getNumberList();
		System.out.println(" nos ---- "+nos);
		for (int i = 0; i < nos.size(); i++) {
			SmsManager sms = SmsManager.getDefault();
//                register();
			String phoneNumber = nos.elementAt(i);
			long sendingTime = System.currentTimeMillis();
			Intent sendingIntent = new Intent(SENT);
			sendingIntent.putExtra(Constants.RECEIVER, phoneNumber);
			sendingIntent.putExtra(Constants.COUNT, (currentCount));
			sendingIntent.putExtra(Constants.SENDING_TIME, sendingTime);
			System.out.println(" sendinf message to "+phoneNumber+" count "+currentCount);
			final int intent_id= (int) System.currentTimeMillis(); 
			PendingIntent sentPI = PendingIntent.getBroadcast(this, intent_id,
					sendingIntent, PendingIntent.FLAG_CANCEL_CURRENT);
			
			Intent receivingIntent = new Intent(DELIVERED);
			receivingIntent.putExtra(Constants.RECEIVER, phoneNumber);
			receivingIntent.putExtra(Constants.SENDING_TIME, sendingTime);

			PendingIntent deliveredPI = PendingIntent.getBroadcast(this, currentCount,
					receivingIntent,
					PendingIntent.FLAG_ONE_SHOT);

			List<String> messages = sms.divideMessage(message);
			for (String msg : messages) {
				sms.sendTextMessage(phoneNumber, null, msg, sentPI,
						deliveredPI);
			}
			
			ContentValues values = new ContentValues();
			values.put(SMSData.MESSAGE, message);
			values.put(SMSData.RECEPIENT, phoneNumber);
			values.put(SMSData.START_TIME, startTime);
			values.put(SMSData.SENT_TIME, sendingTime);
			values.put(SMSData.START_TIME, startTime);
			values.put(SMSData.STATUS, STATUS_SENDING);
			
			getContentResolver().insert(SMSData.CONTENT_URI, values);
		}
	
}


	ProgressDialog progress;
    protected Dialog onCreateDialog(int id, Bundle args) {
    	Dialog dialog = null;
    	switch (id) {
		case Constants.DIALOG_PROGRESSBAR:
			progress = new ProgressDialog(this);
			progress.setTitle("Sending Message, Please wait");
			progress.setMessage("");
			dialog = progress;
			break;
		case Constants.DIALOG_STORE_GROUP:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Info!");
			builder.setMessage("Do you want to save the recepients as a group ?");
			builder.setPositiveButton("Yes", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					showDialog(Constants.DIALOG_ENTER_GROUP_NAME);
				}

				
			});
			builder.setNegativeButton("No", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}

				
			});
			dialog = builder.create();
			break;
		case Constants.DIALOG_ENTER_GROUP_NAME:
			final Dialog groupNameDialog = new Dialog(this);
			groupNameDialog.setTitle("Group Name");
			groupNameDialog.setContentView(R.layout.group_name_dialog);
			
			Button okBtn = (Button) groupNameDialog.findViewById(R.id.group_name_ok);
			okBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					LinearLayout dialog = (LinearLayout)v.getParent();
					EditText nameView = (EditText)dialog.findViewById(R.id.group_name_text);
					String name = nameView.getText().toString();
					if(!TextUtils.isEmpty(name)){
						Cursor c = getContentResolver().query(GroupData.CONTENT_URI, null, GroupData.GROUP_NAME+"=\""+name+"\"", null, null);
						// check if the name is already exist in database
						if(c.getCount() > 0){
							// already exist
							Bundle bundle = new Bundle();
							bundle.putString(Constants.TITLE, "Alert");
							bundle.putString(Constants.TITLE, "The group already exist. please enter a different name.");
							showDialog(Constants.DIALOG_MESSAGE, bundle);
						}else{
							Enumeration<ContactItem> items = Utils.getSelectedContacts().elements();
							while(items.hasMoreElements()){
								ContactItem item = items.nextElement();
								Vector<String> numberList = item.getNumberList();
								for(int i = 0; i<numberList.size(); i++){
									ContentValues values = new ContentValues();
									values.put(GroupData.GROUP_NAME, name);
									values.put(GroupData.PHONE_NUMBER, numberList.elementAt(i));
									getContentResolver().insert(GroupData.CONTENT_URI, values);
								}
							}
							Bundle bundle = new Bundle();
							bundle.putString(Constants.TITLE, "Info");
							bundle.putString(Constants.MESSAGE, "The group is saved successfully.");
							showDialog(Constants.DIALOG_MESSAGE,bundle);
							groupNameDialog.cancel();
							Utils.removeAllContacts();
						}
						c.close();
					}
				}});
			dialog = groupNameDialog;
			break;
		case Constants.DIALOG_MESSAGE:
			dialog = Utils.getDialog(this, args.getString(Constants.TITLE), args.getString(Constants.MESSAGE));
			break;
		case Constants.DIALOG_CONTACT_PICK_LIST:
			
			dialog = Utils.getContactSourceDialog(this);
			break;
		default:
			break;
		}
    	return dialog;
    };
    
    Handler updateHandler = new Handler(){
    	@Override
    	public void handleMessage(Message msg) {
    		// TODO Auto-generated method stub
    		super.handleMessage(msg);
    		
    		switch (msg.what) {
			case MESSAGE_UPDATE_PREOGRESS_BAR_TEXT:
				progress.setMessage((String)msg.obj);
				break;
			case MESSAGE_PREOGRESS_DISMIS:
				progress.cancel();
				break;
			default:
				break;
			}
    	}
    };

	public static final int MESSAGE_UPDATE_PREOGRESS_BAR_TEXT = 1;
	public static final int MESSAGE_PREOGRESS_DISMIS = 2;

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
		// TODO Auto-generated method stub
		if(id == Constants.DIALOG_MESSAGE){
			dialog.setTitle(args.getString(Constants.TITLE));
			((AlertDialog)dialog).setMessage(args.getString(Constants.MESSAGE));
		}
		super.onPrepareDialog(id, dialog, args);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.add_contact:{
			showDialog(Constants.DIALOG_CONTACT_PICK_LIST, null);
			
			}
			break;
		case R.id.send_message:
			//EditText numberView = (EditText)findViewById(R.id.enter_nos);
				sendSMS();
			break;
		case R.id.status:{
			Intent statusActivity = new Intent(getApplicationContext(), StatusActivity.class);
			startActivity(statusActivity);
			}
		break;
		
		case R.id.group_btn:
			Intent groupList = new Intent(this, GroupListActivity.class);
			groupList.putExtra(Constants.LIST_TYPE, Constants.LIST_TYPE_GROUP_EDIT);
			startActivity(groupList);
			break;
		case R.id.schedule_btn:
			Intent scheduleIntent = new Intent(this, ScheduleListActivity.class);
			startActivity(scheduleIntent);
			break;
		default:
			break;
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println("requestCode "+requestCode+" resultCode "+resultCode+" "+data);
		if (resultCode == RESULT_OK) {
			if (data != null) {
				groupLayout.loadSelectedContacts();
			}
		}
	}
	
	public void onToggle(View v){
		groupLayout.onToggle(v);
	}
	
	
}